package com.bizzan.bitrade.interceptor;

import com.bizzan.bitrade.config.InterceptorPathBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.ws.soap.Addressing;
import java.util.List;

@Component
public class AccessControlInterceptor implements HandlerInterceptor {

    @Autowired
    private InterceptorPathBean interceptorPathBean;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        List<String> endpoints = interceptorPathBean.getEndpoints();
        if(endpoints != null && endpoints.size() > 0){
            String requestURI = request.getRequestURI();
            if (endpoints.contains(requestURI)) {
                return true; // 允许访问
            } else {
                //逐个进行模糊匹配
                for (String endpoint : endpoints) {
                    if(requestURI.contains(endpoint)){
                        return true;
                    }
                }
                response.setStatus(HttpServletResponse.SC_FORBIDDEN);
                return false; // 拒绝访问
            }
        }
        return true;
    }
}
